package com.gxa.shop.servlet.evaluate;

import com.alibaba.fastjson.JSON;
import com.gxa.shop.bean.dto.EvaluateQueryPage;
import com.gxa.shop.bean.vo.EvaluateOption;
import com.gxa.shop.commons.r.R;
import com.gxa.shop.service.evaluate.EvaluateService;
import com.gxa.shop.service.evaluate.Impl.EvaluateServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.List;

/**
 * com.gxa.shop.servlet.evaluate
 * User: 刁彦侨
 * Date: 2024/12/24 14:47
 * motto:   逆水行舟不进则退
 * Description:
 * Version: V1.0
 */
@WebServlet(name = "EvaluateFindByPage",value = "/evaluate/findPage")
public class EvaluateFindByPage extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf-8");
        // 获取并验证请求参数
        String str_page = req.getParameter("page");
        String str_limit = req.getParameter("limit");
        String userName=req.getParameter("userName");
        String productName=req.getParameter("productName");

        String evaluateLevel=req.getParameter("evaluateLevel");


        // 创建查询实体

        EvaluateQueryPage evaluateQueryPage = new EvaluateQueryPage();

        // 判断是否有参数并处理
        if (str_page != null && !str_page.trim().isEmpty()) {
            try {
                evaluateQueryPage.setPage(Integer.parseInt(str_page.trim()));
            } catch (NumberFormatException e) {
                evaluateQueryPage.setPage(1);
            }
        }

        if (str_limit != null && !str_limit.trim().isEmpty()) {
            try {
                evaluateQueryPage.setLimit(Integer.parseInt(str_limit.trim()));
            } catch (NumberFormatException e) {
                evaluateQueryPage.setLimit(5);
            }
        }
        evaluateQueryPage.setUserName(userName);
        evaluateQueryPage.setProductName(productName);
        evaluateQueryPage.setEvaluateLevel(evaluateLevel);
        // 初始化服务层对象
        EvaluateService evaluateService = new EvaluateServiceImpl();

        // 满足条件的总条数
        Long total = evaluateService.findByTotal(evaluateQueryPage);

        // 当前页码的数据，默认为空列表
        List<EvaluateOption> list = Collections.emptyList();
        if (total > 0) {
            list = evaluateService.findByPage(evaluateQueryPage);
        }

        // 构建响应数据
        R r = R.ok().addData("total", total).addData("list", list);

        // 响应对象
        PrintWriter writer = resp.getWriter();
        String result = JSON.toJSONString(r);
        System.out.println("FindByPageServlet: " + result);
        writer.write(result);
        writer.flush();
        writer.close();
    }
}
